/*
 * Anything: A flexible and easy to use data structure that combines the 
 * characteristics of a list and a hashmap into one data structure.
 * 
 * Based on a paper by Peter Sommerlad and Marcel Rueedi on 
 * 'Do-it-yourself reflection' entered at EuroPLOP 1998.
 * 
 * This library was written completely from scratch and is based only 
 * in spirit on the original Java Anything implementation written by 
 * Andre Weinand/Marcel Rueedi in 1997/99 and enhanced by Stefan Tramm 
 * in 2006.
 * 
 * Copyright (c) 2008 Thomas Marti and others. All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package any.util;

import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigDecimal;
import java.util.Stack;

import any.Any;
import any.AnyVisitor;
import any.ImmutableAny;
import any.SequentialAny;
import any.impl.util.Utils;

public class Any2JSON extends BasePrinterVisitor implements AnyVisitor<SequentialAny> {

	/**
	 * Anys can mix elements with and without keys in the same data structure, JSON 
	 * on the other hand makes a fixed distinction between <i>arrays</i> (no keys) and 
	 * <i>objects</i> (have keys). Thus when transforming an Any into JSON three strategies 
	 * can be used to deal with this problem:
	 * <ul>
	 *  <li><b>INDEX_AS_KEY:</b> Return a JSON object and use the value of the index as key, where no key is defined.</li>  
	 *  <li><b>OMIT_KEYS:</b> Return a JSON array and omit all keys.</li>  
	 *  <li><b>EXCEPTION:</b> Throw an Exception.</li>  
	 * </ul>
	 */
	public enum Mode {
		/**
		 * 
		 */
		INDEX_AS_KEY,
		
		/**
		 * 
		 */
		OMIT_KEYS,
		
		/**
		 * 
		 */
		EXCEPTION;
	}

	private Stack<Boolean> isArrayStack = new Stack<Boolean>();

	protected Mode mode = Mode.EXCEPTION;
	
	protected boolean asNativeType = true;
	
	public Any2JSON() {
		this(System.out);
	}
	
	public Any2JSON(PrintStream out) {
		super(new PrintWriter(out));
	}

	public Any2JSON(Writer out) {
		super(new PrintWriter(out));
	}
	
	public boolean beginVisit(String key, int index, SequentialAny simpleAny) {
		ImmutableAny any = simpleAny.toAny();
		printSeparator(index);
		println();
		indent();

		printKey(key, index);
		
		boolean isArray;
		if (any.containsKeys() && any.keys().size() != any.size()) {
			switch (mode) {
				case INDEX_AS_KEY:
					isArray = false;
					break;
				case OMIT_KEYS:
					isArray = true;
					break;
				case EXCEPTION:
					throw new RuntimeException("Any cannot be represented as JSON!");
				default:
					throw new AssertionError();
			} 
		} else {
			isArray = !any.containsKeys();			
		}
		
		isArrayStack.push(isArray);

		if (isArray) {
			print("[");
		} else {
			print("{");
		}
		depth++;
		return true;
	}

	public boolean endVisit(String key, int index, SequentialAny simpleAny) {
		depth--;
		println();
		indent();
		if (isArrayStack.pop()) {
			print("]");
		} else {
			print("}");
		}
		
		if (depth == 0) {
			println();
		}
		
		return true;
	}

	public boolean visit(String key, int index, SequentialAny simpleAny) {
		ImmutableAny any = simpleAny.toAny();
		printSeparator(index);
		println();
		indent();

		printKey(key, index);
		
		print(" ");
		
		Object value = (asNativeType ? any.toNative() : any.toObject());
		
		if (value == null || value instanceof BigDecimal || value instanceof Boolean) {
			print(String.valueOf(value));
		} else {
			print(quote(value.toString()));
		}

		return true;
	}

	private void printKey(String key, int index) {
		if (isArrayStack.isEmpty() || isArrayStack.peek()) return;
		
		String printKey = "" + (key == null ? index : key);
		print(quote(printKey) + " : ");
	}
	
	private String quote(String str) {
		return "\"" + Utils.escapeString(str, false) + "\"";
	}
	
	private void printSeparator(int index) {
		if (index > 0) {
			print(", ");
		}
	}
	
	public static void main(String[] args) {
		Any any = Any.create.any();
		any.append(1).append("true").append(new char[] { ' ', '1', 'a', '$' }).put("key1", 1.01).put("key2", true).put("key3", null).append(new Object()).append(new RuntimeException());
		System.out.println(any);
		
		System.out.println("***********************************************");
		
		Any2JSON any2json = new Any2JSON() {{
			mode = Mode.INDEX_AS_KEY;
			asNativeType = true;
		}};
		any.accept(any2json);
	}

}

